//
//  ReleaseFollowVC.m
//  SelfDriving
//
//  Created by apple on 16/2/1.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ReleaseFollowVC.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "BusinessService+FJ.h"
#import "ReleaseCell.h"
#import "IQKeyboardManager.h"
#import <AVKit/AVKit.h>

#import <AVFoundation/AVFoundation.h>
#import "MapViewController.h"
#import "AddMapViewController.h"
@interface ReleaseFollowVC ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,UIVideoEditorControllerDelegate,AddMapViewControllerDatalete,MAMapViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *shareView;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UIButton *qqkj;
@property (weak, nonatomic) IBOutlet UIButton *wx;
@property (weak, nonatomic) IBOutlet UIButton *pyq;
@property (weak, nonatomic) IBOutlet UIButton *wb;
//@property (weak, nonatomic) IBOutlet UIButton *videoBtn;
//@property (weak, nonatomic) IBOutlet UIButton *photoBtn;
@property (weak, nonatomic) IBOutlet UITextField *titlefield;
@property (weak, nonatomic) IBOutlet UIButton *qq;
@property (nonatomic, strong)UISwitch *swit;
@end

@implementation ReleaseFollowVC
{
    NSMutableDictionary *locationdic;
    UIImage *imageData;
    NSURL *VideoPath;
    UIImage *videoImg;
    int filetype;
    MPMoviePlayerController *moviePlayer;
    UIView *shareView;
    NSData *videoData;
    MAMapView *_mapView;
    
    NSString *lianjie;
    NSString *addres;
    int  buttonIndex;
    NSMutableArray *fxdata;
    UITextView *_fxtextField;
    BOOL isOpen;
    NSString *xhwlianje;
    
    NSDictionary *dynamicUrl; //xhw2018-1-29加
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_swit setOn:YES];
    isOpen = YES;
    
    
    fxdata = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"", nil];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
    
    //xhw2018-1-21加
    if (_adUrl) {
        lianjie = _adUrl;
    }
    
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(submitAction:)
     name:@"submitAction"
     object:nil];
    if (lianjie) {
        
    }
    else {
       lianjie = @"添加链接";
    }
//    lianjie = @"添加链接";
    addres = @"自动定位";
    _mapView = [[MAMapView alloc]init];
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    if (_videoUrl) {
        filetype = 2;
        VideoPath = _videoUrl;
        videoData = [NSData dataWithContentsOfURL:VideoPath];
        
    }else{
        filetype = 1;
        imageData = _imgData;
    }
    [_table reloadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getmap:) name:@"getmap" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addphoto:) name:@"addphoto" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addvideo:) name:@"addvideo" object:nil];
}
-(void)addvideo:(NSNotification *)not{
    if ([AppDelegate shareDelegate].isfollowvc == 2 && [AppDelegate shareDelegate].isfollowvc != 0) {
        return;
    }
    //    [[NSNotificationCenter defaultCenter ]postNotificationName:@"dtbackaction" object:_videoUrl];
    filetype = 2;
    VideoPath =  not.object;  //xhw2018-2-12改
//    NSDictionary *xhwDic = not.object;
//    VideoPath = [xhwDic objectForKey:@"videoPath"];
//    videoImg = [xhwDic objectForKey:@"image"];
    videoData = [NSData dataWithContentsOfURL:VideoPath];
    NSLog(@"xhw->ReleaseFollowVC->addvideo->VideoPath->%@",VideoPath);
    NSLog(@"xhw->ReleaseFollowVC->addvideo->videoData->%@",videoData);
    [_table reloadData];
}
-(void)addphoto:(NSNotification *)not{
    if ([AppDelegate shareDelegate].isfollowvc == 2 && [AppDelegate shareDelegate].isfollowvc != 0) {
        return;
    }
    filetype = 1;
    imageData = not.object;
    [_table reloadData];
    [AppDelegate shareDelegate].islod = NO;
}
#pragma mark 获取已经绑定的平台
-(void)initfenxiang{
    /*
    UMSocialSnsPlatform *snsPlatform = nil;
    //微博
    snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    BOOL isOauth = [UMSocialAccountManager isOauthAndTokenNotExpired:snsPlatform.platformName];
    if (isOauth) {
        [fxdata replaceObjectAtIndex:4 withObject:@"sina"];
        _wb.selected = YES;
    }
    
    //空间
    snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQzone];
    BOOL UMShareToQzone = [UMSocialAccountManager isOauthAndTokenNotExpired:snsPlatform.platformName];
    if (UMShareToQzone) {
        [fxdata replaceObjectAtIndex:1 withObject:@"qzone"];
        _qqkj.selected = YES;
    }
    
    //QQ
    snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    BOOL UMShareToQQ = [UMSocialAccountManager isOauthAndTokenNotExpired:snsPlatform.platformName];
    if (UMShareToQQ) {
        [fxdata replaceObjectAtIndex:0 withObject:@"qq"];
        _qq.selected = YES;
    }
    
    //微信
    snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    BOOL UMShareToWechatSession = [UMSocialAccountManager isOauthAndTokenNotExpired:snsPlatform.platformName];
    if (UMShareToWechatSession) {
        [fxdata replaceObjectAtIndex:2 withObject:@"wxsession"];
        _wx.selected = YES;
    }
    
    //朋友圈
    snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatTimeline];
    BOOL UMShareToWechatTimeline = [UMSocialAccountManager isOauthAndTokenNotExpired:snsPlatform.platformName];
    if (UMShareToWechatTimeline) {
        [fxdata replaceObjectAtIndex:3 withObject:@"wxtimeline"];
        _pyq.selected = YES;
    }
     */
    
    
}

#pragma  mark 选择分享平台
- (IBAction)fenxiangAction:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"微博"]) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            [fxdata replaceObjectAtIndex:4 withObject:@"sina"];
        }else{
            [fxdata replaceObjectAtIndex:4 withObject:@""];
        }
    }else if ([sender.titleLabel.text isEqualToString:@"微信"]) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            [fxdata replaceObjectAtIndex:2 withObject:@"wxsession"];
        }else{
            [fxdata replaceObjectAtIndex:2 withObject:@""];
        }
    }else if ([sender.titleLabel.text isEqualToString:@"朋友圈"]) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            [fxdata replaceObjectAtIndex:3 withObject:@"wxtimeline"];
        }else{
            [fxdata replaceObjectAtIndex:3 withObject:@""];
        }
    }else if ([sender.titleLabel.text isEqualToString:@"QQ空间"]) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            [fxdata replaceObjectAtIndex:1 withObject:@"qzone"];
        }else{
            [fxdata replaceObjectAtIndex:1 withObject:@""];
        }
    }else if ([sender.titleLabel.text isEqualToString:@"QQ"]) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            [fxdata replaceObjectAtIndex:0 withObject:@"qq"];
        }else{
            [fxdata replaceObjectAtIndex:0 withObject:@""];
        }
    }
}
-(void)fenxiang{
    UIImage *img;
    if (videoData) {
        img =  [ValidateHelper thumbnailImageForVideo:VideoPath atTime:1];
    }else if(imageData){
        img = imageData;
    } else {
        img = [UIImage imageNamed:@"icon"];
    }
    BOOL includeQzone = NO;
    for (NSString *item in fxdata) {
        if ([item isEqualToString:@"qzone"]) {
            includeQzone = YES;
        }
    }
    if (includeQzone && img == nil) {
        [SVProgressHUD showErrorWithStatus:@"分享到QQ空间必须包含图片和文字说明"];
        return;
    }
    [self fx0:img];
    
    //    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[@"qq"] content:@"测试" image:nil location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeWeb url:@"www.baidu.com"] presentedController:self completion:^(UMSocialResponseEntity * response){
    //        NSLog(@"测试下分享-------->\n%@",response);
    //        if (response.responseCode == UMSResponseCodeSuccess) {
    //            NSLog(@"分享你麻痹");
    //        } else {
    //
    //            NSLog(@"怎么不成功嘛");
    //        }
    //
    //    }];
    
    //    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[@"qq"] content:@"haha" image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:@"www.baidu.com"] presentedController:self completion:^(UMSocialResponseEntity *response) {
    //
    //    }];
    
    
    //    [[UMSocialDataService defaultDataService] postSNSWithTypes:fxdata content:[_fxtextField.text trim].length == 0?@"一米":[_fxtextField.text trim]  image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:nil] presentedController:self completion:^(UMSocialResponseEntity * response){
    //        if (response.responseCode == UMSResponseCodeSuccess) {
    //            [self fx1:img];
    //        } else if(response.responseCode != UMSResponseCodeCancel) {
    //            [SVProgressHUD showImage:nil status:@"分享失败"];
    //            [self fx1:img];
    //        }
    //    }];
}


-(void)fx0:(UIImage *)img{
    NSLog(@"xhw->ReleaseFollowVC->fx0->[AppDelegate sharedInstance].user.nickname->%@",[AppDelegate sharedInstance].user);
    if (fxdata.count < 1) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backAction" object:nil];
        return;
    }
    NSLog(@"xhw->fx0->step21");
    if (((NSString *)[fxdata objectAtIndex:0]).length > 0) {
        NSLog(@"xhw-fx0->step2");
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]发布的动态",[AppDelegate shareDelegate].user.nickname] thumImage:[ValidateHelper imageFromSdcache:url]];
        //设置网页地址
        if (dynamicUrl) {
            shareObject.webpageUrl = dynamicUrl[@"shareurl"];
        }
        else {
            shareObject.webpageUrl = @"www.baidu.com";
        }
        
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                NSLog(@"失败");
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"2" forKey:@"type"];
                    [dic setObject:dynamicUrl[@"dynamic_id"] forKey:@"content"];
                    [dic setObject:@(self.swit.isOn) forKey:@"isopen"];
                    
                    [dic setObject:@"0" forKey:@"isweibo"];
                    [dic setObject:@"0" forKey:@"isweixin"];
                    [dic setObject:@"0" forKey:@"isweixinquan"];
                    [dic setObject:@"0" forKey:@"isqqzone"];
                    [dic setObject:@"1" forKey:@"isqq"];
                    
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
            }
            [self fx1:img];
        }];
//        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[[fxdata objectAtIndex:0]] content:[_fxtextField.text trim].length == 0?@"一米":[_fxtextField.text trim]  image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:url] presentedController:self completion:^(UMSocialResponseEntity * response){
//            [self fx1:img];
//        }];
        
    } else {
        [self fx1:img];
    }
}

-(void)fx1:(UIImage *)img{
    
    if (fxdata.count < 2) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backAction" object:nil];
        return;
    }
    if (((NSString *)[fxdata objectAtIndex:1]).length > 0) {
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]发布的动态",[AppDelegate shareDelegate].user.nickname] thumImage:[ValidateHelper imageFromSdcache:url]];
        //设置网页地址
        //设置网页地址
        if (dynamicUrl) {
            shareObject.webpageUrl = dynamicUrl[@"shareurl"];
        }
        else {
            shareObject.webpageUrl = @"www.baidu.com";
        }
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_Qzone messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                NSLog(@"失败");
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    NSLog(@"成功");
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"2" forKey:@"type"];
                    [dic setObject:dynamicUrl[@"dynamic_id"] forKey:@"content"];
                    [dic setObject:@(self.swit.isOn) forKey:@"isopen"];
                    
                    [dic setObject:@"0" forKey:@"isweibo"];
                    [dic setObject:@"0" forKey:@"isweixin"];
                    [dic setObject:@"0" forKey:@"isweixinquan"];
                    [dic setObject:@"1" forKey:@"isqqzone"];
                    [dic setObject:@"0" forKey:@"isqq"];
                    
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
            }
            [self fx2:img];
        }];
        /*
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[[fxdata objectAtIndex:1]] content:[_fxtextField.text trim].length == 0?@"一米":[_fxtextField.text trim]  image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:url] presentedController:self completion:^(UMSocialResponseEntity * response){
            [self fx2:img];
        }];
         */
    } else {
        [self fx2:img];
    }
}
-(void)fx2:(UIImage *)img{
    
    if (fxdata.count < 3) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backAction" object:nil];
        return;
    }
    if (((NSString *)[fxdata objectAtIndex:2]).length > 0) {
        
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]发布的动态",[AppDelegate shareDelegate].user.nickname] thumImage:[ValidateHelper imageFromSdcache:url]];
        //设置网页地址
        //设置网页地址
        if (dynamicUrl) {
            shareObject.webpageUrl = dynamicUrl[@"shareurl"];
        }
        else {
            shareObject.webpageUrl = @"www.baidu.com";
        }
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                NSLog(@"失败");
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"2" forKey:@"type"];
                    [dic setObject:dynamicUrl[@"dynamic_id"] forKey:@"content"];
                    [dic setObject:@(self.swit.isOn) forKey:@"isopen"];
                    
                    [dic setObject:@"0" forKey:@"isweibo"];
                    [dic setObject:@"1" forKey:@"isweixin"];
                    [dic setObject:@"0" forKey:@"isweixinquan"];
                    [dic setObject:@"0" forKey:@"isqqzone"];
                    [dic setObject:@"0" forKey:@"isqq"];
                    
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
            }
            [self fx3:img];
        }];
        /*
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[[fxdata objectAtIndex:2]] content:[_fxtextField.text trim].length == 0?@"一米":[_fxtextField.text trim]  image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:url] presentedController:self completion:^(UMSocialResponseEntity * response){
            
            [self fx3:img];
        }];
         */
    } else {
        [self fx3:img];
    }
}
-(void)fx3:(UIImage *)img{
    
    if (fxdata.count < 4) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backAction" object:nil];
        return;
    }
    
    if (((NSString *)[fxdata objectAtIndex:3]).length > 0) {
        
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]发布的动态",[AppDelegate shareDelegate].user.nickname] thumImage:[ValidateHelper imageFromSdcache:url]];
        //设置网页地址
        //设置网页地址
        if (dynamicUrl) {
            shareObject.webpageUrl = dynamicUrl[@"shareurl"];
        }
        else {
            shareObject.webpageUrl = @"www.baidu.com";
        }
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                NSLog(@"失败");
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"2" forKey:@"type"];
                    [dic setObject:dynamicUrl[@"dynamic_id"] forKey:@"content"];
                    [dic setObject:@(self.swit.isOn) forKey:@"isopen"];
                    
                    [dic setObject:@"0" forKey:@"isweibo"];
                    [dic setObject:@"0" forKey:@"isweixin"];
                    [dic setObject:@"1" forKey:@"isweixinquan"];
                    [dic setObject:@"0" forKey:@"isqqzone"];
                    [dic setObject:@"0" forKey:@"isqq"];
                    
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
            }
            [self fx2:img];
        }];
        /*
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[[fxdata objectAtIndex:3]] content:[_fxtextField.text trim].length == 0?@"一米":[_fxtextField.text trim]  image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:url] presentedController:self completion:^(UMSocialResponseEntity * response){
            [self fx4:img];
        }];
         */
    } else {
        [self fx4:img];
    }
    
}
-(void)fx4:(UIImage *)img{
    
    if (fxdata.count < 5) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backAction" object:nil];
        return;
    }
    
    if (((NSString *)[fxdata objectAtIndex:4]).length > 0) {
        
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]发布的动态",[AppDelegate shareDelegate].user.nickname] thumImage:[ValidateHelper imageFromSdcache:url]];
        //设置网页地址
        //设置网页地址
        if (dynamicUrl) {
            shareObject.webpageUrl = dynamicUrl[@"shareurl"];
        }
        else {
            shareObject.webpageUrl = @"www.baidu.com";
        }
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_Sina messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                NSLog(@"失败");
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"2" forKey:@"type"];
                    [dic setObject:dynamicUrl[@"dynamic_id"] forKey:@"content"];
                    [dic setObject:@(self.swit.isOn) forKey:@"isopen"];
                    
                    [dic setObject:@"1" forKey:@"isweibo"];
                    [dic setObject:@"0" forKey:@"isweixin"];
                    [dic setObject:@"0" forKey:@"isweixinquan"];
                    [dic setObject:@"0" forKey:@"isqqzone"];
                    [dic setObject:@"0" forKey:@"isqq"];
                    
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
            }
            [self fx2:img];
        }];
        /*
        NSString *url = [lianjie isEqualToString:@"添加链接"]?@"":lianjie;
        [[UMSocialDataService defaultDataService] postSNSWithTypes:@[[fxdata objectAtIndex:4]] content:[_fxtextField.text trim].length == 0?@"一米":[_fxtextField.text trim]  image:img location:nil urlResource:[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:url] presentedController:self completion:^(UMSocialResponseEntity * response){
            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"backAction" object:nil];
        }];
         */
    }
    
}
#pragma  mark 高德
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        _mapView.delegate = nil;
        locationdic = [[NSMutableDictionary alloc]init];
        [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude] forKey:@"lat"];
        [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude] forKey:@"lng"];
        
        CLLocation *c = [[CLLocation alloc] initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
        CLGeocoder *revGeo = [[CLGeocoder alloc] init];
        [revGeo reverseGeocodeLocation:c
                     completionHandler:^(NSArray *placemarks, NSError *error) {
                         if (!error && [placemarks count] > 0)
                         {
                             NSDictionary  *dict = [[placemarks objectAtIndex:0] addressDictionary];
                             NSString *addr = [NSString stringWithFormat:@"%@%@%@",[dict objectForKey:@"City"],[dict objectForKey:@"SubLocality"],[dict objectForKey:@"Name"]];
                             [locationdic setObject:addr forKey:@"addr"];
                             [locationdic setObject:[dict objectForKey:@"City"] forKey:@"cityname"];
                             mapView.delegate = nil;
                         }}];
        
    }
}
////工程启动时保存定位
//-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
//    [locService stopUserLocationService];
//    locationdic = [[NSMutableDictionary alloc]init];
//    [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude] forKey:@"lat"];
//    [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude] forKey:@"lng"];
//    ;
// }
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UITextView class]]) {
        return;
    }
    [self.view endEditing:YES];
}
#pragma mark 发布
-(void)submitAction:(NSNotification *)notification{
    
    [self.view endEditing:YES];
    lianjie = lianjie.length == 0?@"添加链接":lianjie;
    UITextView *cont = (UITextView *)[_table viewWithTag:110];
    //xhw2018-2-3改bug15544:文本内容为必传
    if ([cont.text isEqualToString:@"添加内容"]) {
        [SVProgressHUD showInfoWithStatus:@"请添加内容"];
        return;
    }
    //xhw2018-1-22改bug15307
    [locationdic setObject:[cont.text isEqualToString:@"添加内容"]?@"":cont.text forKey:@"title"];
    [locationdic setObject:cont.text forKey:@"title"];
    [locationdic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];
    [locationdic setObject:[lianjie isEqualToString:@"添加链接"]?@"":lianjie forKey:@"linkurl"];
    [locationdic setObject:@(self.swit.isOn) forKey:@"is_public"];
    [locationdic setObject:@"1" forKey:@"is_share"]; //xhw2018-1-29加
//    NSMutableArray *imgdata =[[NSMutableArray alloc]init];
//    NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
    
    NSMutableArray *dataArr = [[NSMutableArray alloc] init];
    NSMutableDictionary *videoDataDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *videoImgDataDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *imgDataDic = [[NSMutableDictionary alloc] init];

    
    if (videoData) {
        
        NSLog(@"哈哈");
        MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:VideoPath];
        UIImage  *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
        [videoDataDic setObject:@"video" forKey:@"key"];
        [videoDataDic setObject:videoData forKey:@"value"];
        [videoImgDataDic setObject:@"imagefile" forKey:@"key"];
        [videoImgDataDic setObject:UIImagePNGRepresentation(thumbnail) forKey:@"value"];
        [dataArr addObject:videoDataDic];
        [dataArr addObject:videoImgDataDic];
        //        [dici setObject:@"file" forKey:@"key"];
//        [dici setObject:videoData forKey:@"value"];
//
//        [dici setObject:@"imagefile" forKey:@"key"];
//        [dici setObject:UIImagePNGRepresentation(thumbnail) forKey:@"value"];  //xhw2018-2-12加
//
//
//
//        [imgdata addObject:dici];
    }else if(imageData){
        [imgDataDic setObject:@"file" forKey:@"key"];
        [imgDataDic setObject:UIImagePNGRepresentation(imageData) forKey:@"value"];
//        [dici setObject:@"file" forKey:@"key"];
//        [dici setObject:UIImagePNGRepresentation(imageData) forKey:@"value"];
//
//        [imgdata addObject:dici];
        [dataArr addObject:imgDataDic];
    }
    

//    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_dynamicurl postParems:locationdic data:imgdata];
    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_dynamicurl postParems:locationdic data:dataArr];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];
    [SVProgressHUD showWithStatus:@"发送中..."];
}
//- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
//    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
//    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
//    float progres = progress/total;
//
//}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas{
    NSString *request= [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result = [ValidateHelper jsonStringToDictionary:request];
    dynamicUrl = [result objectForKey:@"data"]; //xhw2018-1-29加

    NSLog(@"xhw->dynamicUrl->%@",dynamicUrl);
    int code = [[[result objectForKey:@"state"] objectForKey:@"code"] intValue];
    NSLog(@"xhw->dynamicUrl->state->%d",code);
    if(code == 0){
        [SVProgressHUD dismiss];
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        //xhw2018-1-12改bug14888:要装载了self的mainCtrl pop出栈
        [self.mainCtrl.navigationController popViewControllerAnimated:YES];
        //创建通知
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNotification *notification = [NSNotification notificationWithName:@"public" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
        });
        [self fenxiang];
        
    }else{
        NSLog(@"走到发布失败这里了");
        [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 4;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 90;
    }
    return 45;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 199;
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return @"分享";
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    shareView = _shareView;
    return shareView;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    if(indexPath.section == 0){
        if (indexPath.row == 0) {
            ReleaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rcell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (filetype == 1) {
                //                UIImage  *img = [UIImage imageWithData:imageData];
                cell.bgImg.image = imageData;
                //Modify By Candy
                if (cell.bgImg.image) {
                    [cell.photoBtn setImage:nil forState:UIControlStateNormal];
                    [cell.videoBtn setImage:nil forState:UIControlStateNormal];
                }
                
                [cell.photoBtn addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];
                
            }else if (filetype == 2){
                
                MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:VideoPath];
                UIImage  *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
                cell.bgImg.image = thumbnail;
                //Modify By Candy
                //                cell.photoBtn.hidden = YES;
                //                cell.videoBtn.hidden = YES;
                cell.playBtn.hidden = YES;
                [cell.playBtn addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];
                
            }
            cell.textview.delegate = self;
            if ([cell.textview.text isEqualToString:@"添加内容"]) { //xhw2018-2-1加
                cell.textview.textColor = [UIColor grayColor];
            }
            else {
                cell.textview.textColor = [UIColor blackColor];
            }
            return cell;
        }
        if (indexPath.row == 1) {
            
            cell.textLabel.text = lianjie;
            if ([cell.textLabel.text isEqualToString:@"添加链接"]) { //xhw2018-2-1加
                cell.textLabel.textColor = [UIColor grayColor];
            }
            cell.imageView.image = [UIImage imageNamed:@"flj"];
        }
        if (indexPath.row == 2) {
            cell.textLabel.text = @"公开";
            cell.imageView.image = [UIImage imageNamed:@"fgk_on"];
//            UISwitch *switchs = [[UISwitch alloc]initWithFrame:CGRectMake(SCRE_WIDTH-70, 45/2-15, 90, 30)];
//            [switchs setOn:YES];
//            [switchs addTarget:self action:@selector(isgongkai:) forControlEvents:UIControlEventValueChanged];
//            [cell.contentView addSubview:switchs];
//            self.swit = switchs;
            //xhw2018-1-21改bug15280
            _swit = [[UISwitch alloc]initWithFrame:CGRectMake(SCRE_WIDTH-70, 45/2-15, 90, 30)];
            if (isOpen) {
                [_swit setOn:YES];
            }
            else {
                _swit.on = NO;
            }
            
            [_swit addTarget:self action:@selector(isgongkai:) forControlEvents:UIControlEventValueChanged];
            [cell.contentView addSubview:_swit];
        }
        if (indexPath.row == 3) {
            cell.textLabel.text = addres;
            cell.imageView.image = [UIImage imageNamed:@"fdw"];
        }
    }
    UITextView *cont = (UITextView *)[_table viewWithTag:110];
    _fxtextField = cont;
    return cell;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    [_table reloadData];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSUInteger proposedNewLength = textView.text.length - range.length + text.length;
    if ([textView.text isEqualToString:@"添加内容"]||[textView.text isEqualToString:@"评论"]) {
        textView.text = @"";
    }
    if(text.length==0){
        return YES;
    }
    if (proposedNewLength > 300)
        return NO;//限制长度
    return YES;
}

#pragma mark 是否公开
-(void)isgongkai:(UISwitch *)sw{
    
    if (sw.on) {
        isOpen = YES;
    }
    else {
        isOpen = NO;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //Modify By Candy -- Add
            //            ReleaseCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            //            cell.videoBtn.hidden = YES;
            //            cell.photoBtn.hidden = YES;
        }
        if (indexPath.row == 1) {
            [self titleAction:nil];
        }
        if(indexPath.row == 3){
            [self.view endEditing:YES];
            [[NSNotificationCenter defaultCenter ] postNotificationName:@"tomap" object:nil];
        }
    }
}
-(void)getmap:(NSNotification *)not{
    locationdic = not.object;
    NSLog(@"xhw->发布动态->getMap->addres->%@",[locationdic objectForKey:@"name"]);
    addres = [locationdic objectForKey:@"name"];
    [_table reloadData];
}
#pragma mark 标题
- (void)titleAction:(UIButton *)sender {
    UIAlertController * alertCtrl = [UIAlertController alertControllerWithTitle:@"请输入链接" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertCtrl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        if (lianjie) {
            if ([lianjie isEqualToString:@"添加链接"]) {
                
            }
            else {
               textField.text = lianjie;
            }
            
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField * titleTextField = alertCtrl.textFields.firstObject;
        lianjie = titleTextField.text;
        [_table reloadData];
    }];
    [alertCtrl addAction:cancelAction];
    [alertCtrl addAction:okAction];
    [self presentViewController:alertCtrl animated:YES completion:nil];
    /*
    [self.view endEditing:YES];
    UIAlertView *customAlertView;
    if (customAlertView == nil) {
        customAlertView = [[UIAlertView alloc] initWithTitle:@"请输入连接" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    [customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *nameField = [customAlertView textFieldAtIndex:0];
    customAlertView.tag = 1024;
    nameField.tag = 1025;
    [customAlertView show];
     */
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.view endEditing:YES];
    UITextField *nameField = [alertView textFieldAtIndex:0];
    if (buttonIndex == 1) {
        NSString *url;
        if (![ValidateHelper isHttpHead:nameField.text]) {
            url = [NSString stringWithFormat:@"http://%@",nameField.text];
        }
        lianjie = url;
        [_table reloadData];
    }
}
- (IBAction)photoAction:(UIButton *)sender {
    [AppDelegate shareDelegate].islod = NO;
    [AppDelegate shareDelegate].isfollowvc = 1;
    [[NSNotificationCenter defaultCenter ]postNotificationName:@"tophoto" object:nil];
}
- (IBAction)vidoAction:(UIButton *)sender {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted ||  authStatus ==AVAuthorizationStatusDenied){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
    imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
    
    NSArray *arrMediaTypes=[NSArray arrayWithObjects: requiredMediaType1,nil];
    imagePickerVC.mediaTypes = arrMediaTypes;
    imagePickerVC.delegate = self;
    imagePickerVC.allowsEditing = YES;
    [self presentViewController:imagePickerVC
                       animated:NO
                     completion:nil];
    //
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    imageData = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage],0.00001);
    if(imageData){
        filetype = 1;
        [_table reloadData];
    }else{
        VideoPath = [info valueForKey:UIImagePickerControllerMediaURL];
        videoData = [NSData dataWithContentsOfURL:VideoPath];
        filetype = 2;
        [_table reloadData];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    CGRect f =  _table.frame;
    f.origin.y = 118;
    _table.frame = f;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    CGRect f =  _table.frame;
    f.origin.y = 118;
    _table.frame = f;
}
-(void)videoEditorControllerDidCancel:(UIVideoEditorController *)editor{
    [editor dismissViewControllerAnimated:YES completion:nil];
    CGRect f =  _table.frame;
    f.origin.y = 118;
    _table.frame = f;
}
-(void)videoEditorController:(UIVideoEditorController *)editor didSaveEditedVideoToPath:(NSString *)editedVideoPath{
    [editor dismissViewControllerAnimated:YES completion:nil];
    CGRect f =  _table.frame;
    f.origin.y = 118;
    _table.frame = f;
}

#pragma mark 播放
-(void)playVideo{
    moviePlayer = [ValidateHelper bofang:VideoPath];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:moviePlayer.view];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
}
#pragma  mark 视频播放
- (void)playVideoFinished:(NSNotification *)theNotification{
    self.navigationController.navigationBarHidden = NO;
    // 取消监听
    [[NSNotificationCenter defaultCenter]
     removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
    // 将视频视图从父视图中删除
    [moviePlayer.view removeFromSuperview];
}

// 获取视频第一帧
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}


@end
